/** 
 * 系统的路由服务
*/
const fs = require('fs');
const path = require('path');
const url = require('url');
let ROOT_PATH = path.resolve('../');
console.log(ROOT_PATH)
/*
 * 获取文件类型的方法，私有方法，不暴露
 */
function getMime(exename, callback){
    fs.readFile(ROOT_PATH + '/mime.json', (err, data) =>{
        if(err){
            console.log('mime.json文件不存在');
            return false;
        }

        let Mimes = JSON.parse(data.toString());
        let result = Mimes[exename] || 'text/html';
        callback(result);
    });
}
/** 
 * 对外暴露的方法，获取文件内容并响应
*/
exports.statics = function(req, res, staticPath){
    let pathname = url.parse(req.url).pathname;
    if(pathname == '/'){
        pathname = '/inex.html';   //默认加载首页
    }
    
    let extname = path.extname(pathname);
    if(pathname != '/favicon.ico'){
        fs.readFile(staticPath + '/' + pathname, (error, data404)=>{
            if(error){
                console.log('404');
            }
            res.writeHead(404, {"Content-Type":"text/html;charset='utf-8'"});
            res.write(data404);
            res.end();
        });
    }
    else{
        getMime(exename, (mime)=>{
            res.writeHead(200,{"Content-Type":""+mime+";charset='utf-8'"})
                .write(data)
                .end();
        })
    }
}